﻿#region

using System.Text.Json;
using System.Text.Json.Serialization;
using Vin.Tool.Core.JsonCategory.TimeFormat;

#endregion

namespace Vin.Tool.Core.JsonCategory.Converters;

public class DateTimeConverter<T> : JsonConverter<DateTime?> where T : ITimeFormat, new()
{
    private readonly T _timeFormat;

    public DateTimeConverter()
    {
        _timeFormat = new T();
    }

    public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = reader.GetString();
        if (string.IsNullOrEmpty(value))
            return null;
        return DateTime.Parse(value);
    }

    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
    {
        if (value.HasValue) writer.WriteStringValue(value.Value.ToString(_timeFormat.Format()));
    }
}

public class DateTimeConverter : DateTimeConverter<YYYYMMSSHHmmssFormat>;